//
//  QMakeInvoiceVC.m
//  QoilPublic
//
//  Created by 杨凯 on 2017/2/22.
//  Copyright © 2017年 杨凯. All rights reserved.
//

#import "QMakeInvoiceVC.h"
#import "QMakeInvoiceCell.h"
#import "QCustomerOrderCell.h"//订单 section ==1
#import "QInvoiceOrderVC.h"
#import "QInfoManageVC.h"
#import "QOrderModel.h"
#import "QMakeInvoiceModel.h"
@interface QMakeInvoiceVC ()<UITableViewDelegate,UITableViewDataSource>
{
    NSString *_orderIds,*_orderAmount,*_invoiceType,*_credentialsId,*_userType,*_startDate,*_endDate;
}
@property (nonatomic,strong)UITableView *tbView;
@property (nonatomic,strong)NSMutableArray *titleArr;
@property (nonatomic,strong)NSMutableArray *dataArr;
@property (nonatomic,strong)QMakeInvoiceModel *model;
@property (nonatomic,strong)QInvoiceListModel *listModel;

@end

@implementation QMakeInvoiceVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"开票";
    [self createUI];
}

- (void)createUI{
    _titleArr =[NSMutableArray arrayWithObjects:@"开票人信息",@"发票类型",@"开票金额",@"开票税费", nil];
    [self.view addSubview:self.tbView];
    [self.tbView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo (@0);
    }];
    UIView *header =[[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 60)];
    UILabel *titleLab =[QViewUtility createLabelWithFrame:CGRectMake(25, 6, 100, 10) font:Ksize12 textAlignment:0 textColor:[QColorUtility defaultRedColor] text:@"提示:"];
    [header addSubview:titleLab];
    
    UILabel *lab =[QViewUtility createLabelWithFrame:CGRectMake(25, 16, kScreenWidth, 20) font:Ksize13 textAlignment:0 textColor:[QColorUtility defaultDeepGrayColor] text:@"1、申请开票后，一个星期可以邮寄发票"];
    [header addSubview:lab];
    
       UILabel *lab1 =[QViewUtility createLabelWithFrame:CGRectMake(25, 36, kScreenWidth, 20) font:Ksize13 textAlignment:0 textColor:[QColorUtility defaultDeepGrayColor] text:@"2、订单开票有效期2个月，超过则不能开票"];
    [header addSubview:lab1];
    
    self.tbView.tableHeaderView =header;
    [self.tbView registerNib:[UINib nibWithNibName:@"QMakeInvoiceCell" bundle:nil] forCellReuseIdentifier:@"QMakeInvoiceCell"];
    [self.tbView registerNib:[UINib nibWithNibName:@"QCustomerOrderCell" bundle:nil] forCellReuseIdentifier:@"QCustomerOrderCell"];
    
    //提交
    UIView * footer =[[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 100)];
    UIButton * btn =[QViewUtility createButtonWithFrame:CGRectMake(40, 35, kScreenWidth - 80, 45) font:Ksize17 title:@"提交" titleColor:[UIColor whiteColor] backgroundColor:[QColorUtility defaultBlueColor]];
    [btn addTarget:self action:@selector(submitAction) forControlEvents:UIControlEventTouchUpInside];
    btn.layer.cornerRadius = 7;
    btn.clipsToBounds = YES;
    [footer addSubview:btn];
    self.tbView.tableFooterView = footer;
}
#pragma mark --- 提交
- (void)submitAction{
    WS(wSelf);
    if ([_credentialsId isEqualToString:@""]||_credentialsId ==nil) {
        [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"请选择信息" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
    
        return;
    }
    if ([_orderIds isEqualToString:@""]||_orderIds==nil) {
        [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"请选择订单" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        return;
    }
    NSString * url =[QParamService urlWithAction:@"createBilling"];
    NSDictionary * para = [QParamService createBillingWithOrderIds:_orderIds OrderAmount:_model.orderMoney InvoiceType:_listModel.invoiceType CredentialsId:_credentialsId UserType:_listModel.cusType StartDate:_startDate EndDate:_endDate];
    
    [QViewUtility showMBHudToView:self.view hideBg:NO];
    [[QHttpManager sharedManager] POST:url parameterMD5:para completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [QViewUtility hideMBHudToView:self.view];
        if (error) {
            return ;
        }
        QBaseModel *baseModel =[QBaseModel objectFromDict:dict];
        if ([baseModel.result isEqualToString:@"success"]) {
            [wSelf.navigationController popViewControllerAnimated:YES];
            
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:baseModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];

        }
    }];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section ==1) {
        return 50;
    }
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section ==1) {
        return 50;
    }
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section ==1) {
        return 40;
    }
    return 50;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        UIView * header =[[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
        header.backgroundColor =[UIColor whiteColor];
        UILabel *lab =[QViewUtility createLabelWithFrame:CGRectMake(23, 15, 100, 20) font:Ksize15 textAlignment:0 textColor:[QColorUtility defaultBackColor] text:@"开票订单"];
        [header addSubview:lab];
        return header;
    }
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 1) {
        UIView * footer =[[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
        footer.backgroundColor =[UIColor whiteColor];
        UILabel *lab1 =[UILabel new];
        lab1.font = [UIFont systemFontOfSize:Ksize15];
        lab1.textColor = [QColorUtility defaultRedColor];
        [footer addSubview:lab1];
        [lab1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo (@-22);
            make.height.equalTo(@20);
            make.top.equalTo(@15);
        }];
        if (_model!=nil&&![_model.orderMoney isEqualToString:@""]) {
            lab1.text = [NSString stringWithFormat:@"%@元",_model.orderMoney];
        }else{
            lab1.text = @"0.00元";
        }
        
        UILabel *lab =[UILabel new];
        [footer addSubview:lab];
        lab.font = [UIFont systemFontOfSize:Ksize16];
        lab.textColor = [QColorUtility defaultBackColor];
        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo (@20);
            make.top.equalTo(@15);
            make.right.mas_equalTo(lab1.mas_left).offset(-8);
        }];
        lab.text =@"合计:";
        
        UIView *line =[UIView new];
        [footer addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo (@20);
            make.right.equalTo (@-20);
            make.top.equalTo (@0);
            make.height.equalTo(@.7);
        }];
        line.backgroundColor =[QColorUtility defaultLineColor];
        
        
        
        return footer;
        
    }
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 4;
    }
    return self.dataArr.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section ==0) {
        QMakeInvoiceCell * cell= [tableView dequeueReusableCellWithIdentifier:@"QMakeInvoiceCell" forIndexPath:indexPath];
        cell.textField.hidden = YES;
        cell.codeBtn.hidden = YES;
        cell.titleLabe.text =_titleArr[indexPath.row];
        if (indexPath.row ==0) {
            cell.secondLab.text =@"请选择开票人信息";
            cell.iconImg.hidden =NO;
            if (_listModel!=nil&&![_listModel.receiveName isEqualToString:@""]) {
                cell.secondLab.text =@"";
                cell.thirdLab.text = [NSString stringWithFormat:@"%@  %@",_listModel.receiveName,_listModel.receivePhone];
                cell.thirdLab.textColor = [QColorUtility defaultBackColor];
                cell.thirdLab.hidden = NO;
            }
            
        }else if (indexPath.row ==1){
            cell.secondLab.text =@"无";
            if ([_listModel.invoiceType isEqualToString:@"1"]) {
                cell.secondLab.text = @"普票";
            }else if ([_listModel.invoiceType isEqualToString:@"2"]){
                cell.secondLab.text = @"专票";
            }
            cell.secondLab.textColor =[QColorUtility defaultBlueColor];
        }else if (indexPath.row ==2){
            cell.secondLab.text =@"请选择开票订单";
            cell.iconImg.hidden =NO;
            if (![_model.orderMoney isEqualToString:@""]&&_model!=nil) {
                cell.secondLab.text = _model.orderMoney;
                cell.secondLab.textColor = [QColorUtility defaultRedColor];
                cell.thirdLab.hidden = NO;
                cell.thirdLab.text = [NSString stringWithFormat:@"元(%@个订单)",_model.orderNum];
                
            }
        }else if (indexPath.row ==3){
            cell.secondLab.textColor =[QColorUtility defaultRedColor];
            cell.secondLab.text =@"0";
            if (_model!=nil&&![_model.taxation isEqualToString:@""]) {
                cell.secondLab.text = _model.taxation;
            }
            cell.thirdLab.hidden =NO;
        }
        
        return cell;

    }else{
        
        QCustomerOrderCell *cell =[tableView dequeueReusableCellWithIdentifier:@"QCustomerOrderCell"];
        QOrderModel * model = self.dataArr[indexPath.row];
        cell.titleLab.text = model.orderType;
        cell.priceLab.text = [NSString stringWithFormat:@"￥%@",model.amount];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    WS(wSelf);

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0&&indexPath.row ==0) {
        QInfoManageVC * vc =[[QInfoManageVC alloc]init];
        vc.popToWhere = @"QMakeInvoiceVC";
        vc.state = @"1";//传1开票信息管理界面只请求已通过的信息管理
        vc.InformationBlock = ^(QInvoiceListModel * model){
            _credentialsId = model.credentialsId;
            _listModel = model;
            _invoiceType = model.invoiceType;
            [wSelf.tbView reloadData];
            
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (indexPath.section == 0&&indexPath.row ==2) {
        
        if (_invoiceType == nil||[_invoiceType isEqualToString:@""]) {
            
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"请先选择开票信息" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
            return;
        }
        QInvoiceOrderVC * vc =[[QInvoiceOrderVC alloc]init];
        [self.dataArr removeAllObjects];
        vc.OrderBlock = ^(NSMutableArray * arr,QInvoiceOrderModel *model){
            
            [wSelf.dataArr addObjectsFromArray:arr];
            [wSelf.tbView reloadData];
            //[wSelf requestData];
            [wSelf requestData:model];
            _startDate = model.startDate;
            _endDate = model.endDate;
            
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
}
//获取开票订单总金额,税费
- (void)requestData:(QInvoiceOrderModel *)model{
    NSString * url =[QParamService urlWithAction:@"findInvoiceOrderMoney"];
    NSMutableArray * orderIdsArr =[NSMutableArray array];

    CGFloat money = 0.0;

    for (QOrderModel * orderModel in self.dataArr) {
        [orderIdsArr addObject:orderModel.orderId];
        money = [orderModel.amount floatValue]+money;
        
    }
    NSString * amount = [NSString stringWithFormat:@"%.2f",money];
    //NSString * new =@"";
    _orderIds =@"";
    for (NSString * str in orderIdsArr) {
        _orderIds =[NSString stringWithFormat:@"%@,%@",str,_orderIds];
    }
    NSDictionary * para = [QParamService findInvoiceOrderMoneyWithOrderIds:_orderIds OrderAmount:amount InvoiceType:_invoiceType StartDate:model.startDate EndData:model.endDate];
    
    [[QHttpManager sharedManager] POST:url parameterMD5:para completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error) {
            return ;
        }
        QBaseModel * baseModel =[QBaseModel objectFromDict:dict];
        if ([baseModel.result isEqualToString:@"success"]) {
            _model = [QMakeInvoiceModel objectFromDict:baseModel.items];
            [_tbView reloadData];
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:baseModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];

        }
    }];
}

- (UITableView*)tbView {
    if (!_tbView) {
        _tbView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tbView.dataSource = self;
        _tbView.delegate = self;
        _tbView.backgroundColor = [UIColor clearColor];
        _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tbView;
}

- (NSMutableArray*)dataArr{
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
